import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建 axios 实例
const request = axios.create({
    baseURL: '/api',  // 添加 /api 前缀
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    },
    withCredentials: true
})

// 请求拦截器
request.interceptors.request.use(
    config => {
        // 打印请求信息
        console.log('Request:', {
            url: config.url,
            method: config.method,
            data: config.data,
            headers: config.headers
        })

        const token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    error => {
        console.error('Request error:', error)
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    response => {
        // 打印响应信息
        console.log('Response:', response.data)
        return response.data
    },
    error => {
        console.error('Response error:', {
            status: error.response?.status,
            data: error.response?.data,
            error: error
        })

        const message = error.response?.data?.error || error.message || '请求失败'
        ElMessage.error(message)

        if (error.response?.status === 401) {
            localStorage.removeItem('token')
            window.location.href = '/login'
        }

        return Promise.reject(new Error(message))
    }
)

export { request } 